package handlers;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;

import server.Server;

@SuppressWarnings("resource")
public class Machines {
	public static String getMachineFile() throws IOException{
		String result = "";
		String line = "";
		File machines = new File("machines.txt");

		BufferedReader br = new BufferedReader(new FileReader(machines));
		while ((line = br.readLine()) != null){
			result += line;
		}
		return result;
	}
	
	public static HashMap<String, String> getMachineList() throws IOException{
		HashMap<String, String> aList = new HashMap<String, String>();
		int length = getMachineFile().length();
		String src = getMachineFile().substring(2, length-2);
		String[] machines = src.split("\\],\\[");
		for(String c:machines){
			String[] s = c.split(",");
			String s1 = s[0].substring(1,s[0].length()-1).toLowerCase();
			String s2 = s[1].substring(1,s[1].length()-1).toLowerCase();
			aList.put(s1, s2);
		}
		return aList;
	}
	
	public static String writeContacts(Server ws, boolean kirjutan) throws IOException{
		HashMap<String, String> mList = ws.getMachines();
		BufferedWriter fw = new BufferedWriter(new FileWriter("machines.txt"));
		String result = "";
		int i = 1;
		int size = mList.keySet().size();
		result += "[\n";
		for(String IP: mList.keySet()){
			if(i == size){
				result += "[\"" + IP.toLowerCase() + "\",\"" + mList.get(IP).toLowerCase() + "\"]\n";
			}else{
				result += "[\"" + IP.toLowerCase() + "\",\"" + mList.get(IP).toLowerCase() + "\"],\n";
			}
			i++;
		}
		result += "]";
		if(kirjutan){
			fw.write(result);
		}
		fw.close();
		return result;
	}
	
	public static void addMachine(String IP, int port) throws IOException{
		HashMap<String, String> machines = getMachineList();
		if(!machines.containsKey(IP)){
			machines.put(IP, Integer.toString(port));
		}
	}
}
